

(function(){
	KeyCommander = G.GClass('Widget', 'KeyCommander');

	KeyCommander.prototype.__init = function(cmdlist) {
		this._buf = [];
		this._cmdList = cmdlist || {};
		this._enabled = false;
		this._filtered = [];
		this._timeout = 1000;
	}

	KeyCommander.prototype.enable = function()
	{
		G(document).bind('onkeypress', this.on_key, this);
		this._filtered = this._cmdList;
	}

	KeyCommander.prototype.disable = function()
	{
		G(document).unbind('onkeypress', on_key, this);
	}

	KeyCommander.prototype.load_cmd_list = function(cmdlist) 
	{
		this._cmdList = cmdlist;
		this._filtered = this._cmdList;
	}


	KeyCommander.prototype.on_key = function(evt) 
	{
		var k = String.fromCharCode(evt.which || evt.keyCode);

		if (k in this._filtered) {
			cmd = this._filtered[k];
			if (typeof(cmd.func) == 'function') {
				cmd.func.call(cmd.obj);
				this._filtered = this._cmdList;
			} else {
				this._filtered = cmd;		// Wait further key
			}
		} else {	
			// Error cmd, go back to begining.
			// Todo: make a beep on a unexpected key
			this._filtered = this._cmdList;
			console.log('unsupported command.');
		}

		if (this._timer == null) {
			var _self = this;
			this._timer = setTimeout(function() {
				_self.on_timeout();
			}, this._timeout);
		} else {
			clearTimeout(this._timer);
		}

	}

	KeyCommander.prototype.on_timeout = function()
	{
		this._filtered = this._cmdList;
	}
 })();

